package com.atguigu.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.reggie.common.BaseContext;
import com.atguigu.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.print.attribute.standard.MediaSize;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.LogRecord;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-10-09 17:13
 */

/**
 * 自定义过滤器
 * 检查用户是否完成登陆
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        // 定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        // 2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        // 3、如果不需要处理直接放行
        if (check){
            log.info("本次请求{}不需要处理",request.getRequestURI());
            filterChain.doFilter(request,response);
            return;
        }

        // 4-1、判断客户端用户登陆状态，如果已经登陆，则直接放行
        if( request.getSession().getAttribute("employee") != null){
            log.info("用户已登陆，用户id为：{}",request.getSession().getAttribute("employee"));
            Long empId = (Long) request.getSession().getAttribute("employee");
            // 通过BaseContext设置当前登陆用户的id值
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        // 4-2、判断移动端用户登陆状态，如果已经登陆，则直接放行
        if( request.getSession().getAttribute("user") != null){
            log.info("用户已登陆，用户id为：{}",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            // 通过BaseContext设置当前登陆用户的id值
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }


        log.info("用户未登录+{}",request.getRequestURI());
        // 5、如果未登录则返回未登录结果，通过输出流方式向前端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    public boolean check(String[] urls,String requestURI){
        boolean match;
        for (String url : urls){
            match = PATH_MATCHER.match(url, requestURI);
            if (match == true){
                return true;
            }
        }
        return false;
    }
}
